from django import http
import pickle
import base64
from django_redis import get_redis_connection

def merge_cookie_redis_data(request,user,response) -> http.HttpResponse:
    """
    :param request: 请求对象，为了获取cookie中的数据
    :param user: 用户对象，为了获取redis中的数据
    :param response: 为了清空cookie数据
    :return: 响应对象
    """
    # 1，获取cookie数据
    cookie_cart = request.COOKIES.get("carts")

    # 2，转换cookie数据为字典
    cookie_cart_dict = {}
    if cookie_cart:
        cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
    else:
        return response

    # 3, 数据合并到redis
    redis_conn = get_redis_connection("carts")
    for sku_id,selected_count in cookie_cart_dict.items():
        # 获取redis中商品数量
        redis_sku_count = redis_conn.hget(f"carts_{request.user.id}", sku_id)

        # 判断redis中是否存在cookie对应的商品
        if redis_sku_count:
            redis_sku_count = int(redis_sku_count.decode())
        else:
            redis_sku_count = 0

        # 大小判断，并设置值
        if selected_count["count"] > redis_sku_count:
            redis_conn.hset(f"carts_{request.user.id}",sku_id,selected_count["count"])

            # 判断cookie中商品选中状态
            if selected_count["selected"]:
                redis_conn.sadd(f"selected_{request.user.id}", sku_id)
            else:
                redis_conn.srem(f"selected_{request.user.id}", sku_id)

    # 4, 清空cookie数据
    response.delete_cookie("carts")

    # 5，返回响应
    return response

